"""
服务层使用示例
展示如何使用重构后的恐贪指标服务层
"""

import asyncio
import pandas as pd
from datetime import datetime
import logging

# 导入各个服务层
from .fear_greed_processor import fear_greed_processor
from .fear_greed_service import fear_greed_service

# 模型层已移除 - 直接使用服务层

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def example_market_data_service():
    """演示市场数据服务的使用"""
    print("\n=== 市场数据服务示例 ===")
    
    # 1. 获取单个股票数据
    symbol = "AAPL.US"
    print(f"获取 {symbol} 的股票数据...")
    
    df = await fear_greed_service.get_stock_data(symbol, 60)
    print(f"获取到 {len(df)} 天的数据")
    print(f"最新价格: {df['Close'].iloc[-1] if not df.empty else 'N/A'}")
    
    # 2. 批量获取多个股票数据
    symbols = ["AAPL.US", "GOOGL.US", "MSFT.US"]
    print(f"\n批量获取股票数据: {symbols}")
    
    stocks_data = await fear_greed_service.get_multiple_stocks_data(symbols, 30)
    for symbol, data in stocks_data.items():
        print(f"{symbol}: {len(data)} 天数据")
    
    # 3. 检查数据源状态
    print(f"\n数据源状态: {fear_greed_service.get_data_source_status()}")


def example_calculation_service():
    """演示计算服务的使用（使用模拟数据）"""
    print("\n=== 计算服务示例 ===")
    
    # 创建模拟数据
    dates = pd.date_range(start='2024-01-01', periods=100, freq='D')
    data = {
        'Open': [100 + i * 0.1 for i in range(100)],
        'High': [101 + i * 0.1 for i in range(100)],
        'Low': [99 + i * 0.1 for i in range(100)],
        'Close': [100.5 + i * 0.1 for i in range(100)],
        'Volume': [1000000 + i * 1000 for i in range(100)]
    }
    df = pd.DataFrame(data, index=dates)
    
    # 计算恐贪指标
    print("使用模拟数据计算恐贪指标...")
    result = fear_greed_processor.calculate_fear_greed_index_from_data(df, "TEST.US")
    
    print(f"恐贪指数: {result['fear_greed_index']}")
    print(f"情绪状态: {result['sentiment']}")
    print(f"投资建议: {result['investment_advice']}")
    print(f"组件分数: {result['components']}")
    
    # 计算历史恐贪指标
    print("\n计算历史恐贪指标...")
    history = fear_greed_processor.calculate_historical_fear_greed(df, "TEST.US")
    print(f"历史数据点: {len(history)}")
    if history:
        print(f"最新记录: {history[-1]}")


async def example_business_service():
    """演示业务服务的使用"""
    print("\n=== 业务服务示例 ===")
    
    symbol = "AAPL.US"
    
    try:
        # 1. 计算单个股票的恐贪指标
        print(f"计算 {symbol} 的恐贪指标...")
        result = await fear_greed_service.calculate_fear_greed_index(symbol)
        
        print(f"股票: {result['symbol']}")
        print(f"当前价格: {result['current_price']}")
        print(f"恐贪指数: {result['fear_greed_index']}")
        print(f"情绪状态: {result['sentiment']}")
        print(f"投资建议: {result['investment_advice']}")
        
        # 2. 批量计算
        symbols = ["AAPL.US", "GOOGL.US"]
        print(f"\n批量计算恐贪指标: {symbols}")
        batch_results = await fear_greed_service.calculate_batch_fear_greed_index(symbols)
        
        for symbol, result in batch_results.items():
            if 'error' in result:
                print(f"{symbol}: 计算失败 - {result['error']}")
            else:
                print(f"{symbol}: {result['fear_greed_index']} ({result['sentiment']})")
        
        # 3. 获取历史数据
        print(f"\n获取 {symbol} 的历史恐贪指标...")
        history = await fear_greed_service.get_fear_greed_history(symbol, 30)
        print(f"历史数据点: {len(history)}")
        
        # 4. 趋势分析
        print(f"\n分析 {symbol} 的趋势...")
        trend_analysis = await fear_greed_service.analyze_stock_trend(symbol, 10)
        print(f"趋势分析完成，数据点: {trend_analysis['summary'].get('data_points', 0)}")
        
        # 5. 服务状态
        print(f"\n服务状态: {fear_greed_service.get_service_status()}")
        
    except Exception as e:
        print(f"业务服务示例执行失败: {e}")


async def example_processor_direct():
    """演示直接使用处理器的示例"""
    print("\n=== 处理器直接使用示例 ===")
    
    try:
        # 创建模拟数据
        dates = pd.date_range(start='2024-01-01', periods=50, freq='D')
        data = {
            'Open': [100 + i * 0.2 for i in range(50)],
            'High': [102 + i * 0.2 for i in range(50)],
            'Low': [98 + i * 0.2 for i in range(50)],
            'Close': [101 + i * 0.2 for i in range(50)],
            'Volume': [1000000 + i * 5000 for i in range(50)]
        }
        df = pd.DataFrame(data, index=dates)
        
        # 直接使用处理器计算
        print("直接使用恐贪处理器...")
        result = fear_greed_processor.calculate_fear_greed_index_from_data(df, "DEMO.US")
        
        print(f"恐贪指数: {result['fear_greed_index']}")
        print(f"情绪状态: {result['sentiment']}")
        print(f"投资建议: {result['investment_advice']}")
        
        # 获取处理器配置
        print(f"\n处理器配置:")
        indicators = fear_greed_processor.indicators
        for name, weight in indicators.items():
            print(f"{name}: {weight}")
        
    except Exception as e:
        print(f"处理器直接使用示例执行失败: {e}")


async def main():
    """主函数，演示所有服务的使用"""
    print("恐贪指标服务层使用示例")
    print("=" * 50)
    
    # 1. 市场数据服务示例
    await example_market_data_service()
    
    # 2. 计算服务示例
    example_calculation_service()
    
    # 3. 业务服务示例
    await example_business_service()
    
    # 4. 处理器直接使用示例
    await example_processor_direct()
    
    print("\n示例执行完成！")


if __name__ == "__main__":
    # 运行示例
    asyncio.run(main())
